package com.hwpt.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许来自前端地址的跨域请求
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        // 允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许的头部信息
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With", "Origin", "Accept"));
        // 允许携带认证信息（如cookie）
        configuration.setAllowCredentials(true);
        // 预检请求的缓存时间（秒）
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口路径应用此CORS配置
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 启用CORS支持，并使用上面的配置
                .cors().configurationSource(corsConfigurationSource()).and()
                .authorizeRequests()
                // 让Spring Security放行所有请求，具体的权限验证交给JWT拦截器
                .antMatchers("/**").permitAll()
                .anyRequest().permitAll()
                .and()
                // 禁用CSRF，因为JWT是无状态的，不需要CSRF保护
                .csrf().disable()
                // 禁用Session管理，使用无状态JWT
                .sessionManagement().disable()
                // 禁用默认的登录页和登出页
                .formLogin().disable()
                .logout().disable()
                // 禁用Basic认证
                .httpBasic().disable();
    }
}